# coding: utf-8
# using python3.7
import sys
import json
from base64 import b64encode
# if sys.version_info.major == 2:
#     from urllib import pathname2url as quote
# else: # is 3
from urllib.parse import quote
import argparse
import os


help_msg = """
从ss的配置文件中提取ss链接以便直接导入Mac的ShadowsocksX-NG。
配置文件下载自 shadowsocks.com 的服务。
适用于1.8.0版本ShadowsocksX-NG。
"""

def transfer2uri(cfg):
    b64 = b64encode(bytes('%s:%s' % (cfg['method'], cfg['password']), encoding='utf-8'))
    remark = quote(cfg['remarks'], encoding='utf-8', safe = ',:')
    url = 'ss://%s@%s:%s/?#%s' % (str(b64, encoding='utf-8'), cfg['server'], cfg['server_port'], remark)
    return url


def main(path_arg, transfer_func=transfer2uri):
    with open(path_arg) as fp:
        obj = json.loads(fp.read())
    urls = [transfer_func(cfg) for cfg in obj['configs']]
    return '\n'.join(urls)


if __name__ == '__main__':
    default_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'local', 'ss', 'gui-config.json')
    # print(os.listdir(os.path.dirname(default_path)))
    parser = argparse.ArgumentParser(description=help_msg)
    parser.add_argument('-c', '--config', type=str, default=default_path,
                        help='Location of configuration json file. Default: `../../../local/ss/gui-config.json`')
    args = parser.parse_args()

    print(main(args.config))
